package com.wjjun.data.uitls;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Gson解析器
 * 时间戳转Date
 */
public class DateJsonDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.getAsJsonPrimitive().isNumber()) {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }
        if(json.getAsString().length()==13){
            return new Date(Long.valueOf(json.getAsString()));
        }

        Date date = null;
        DateFormat formatter =null;
        if(json.getAsString().length()==10){
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        }else {
         formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}
        try {
            date = formatter.parse(json.getAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
}
